import { ElMessage } from 'element-plus'
import { nanoid } from 'nanoid'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { deleteConversation, getConversationDetail, getConversationsList, getRecommendedQuestions } from '../services/apiService'


export const useChatStore = defineStore('chatStore',() => {
  
  const chatSessions = ref([])
  const currentChatId = ref(null)
  const isSidebarCollapsed = ref(false)
  // 推荐问题
  const recommendedQuestions = ref([])
  const isSending = ref(false)

  // 获取当前对话
  const currentChat = computed(() => {
    console.log(111111111, currentChatId.value)
    return chatSessions.value.find(chat => chat.session_id === currentChatId.value)
  })

  // 创建新对话
  const createNewChat = () => {
    const newChat = {
      id: nanoid(),
      session_id: nanoid(),
      title: '新对话',
      messages: [],
      created_at: new Date(),
      isNew: true
    }
    currentChatId.value = newChat.session_id
    chatSessions.value.unshift(newChat)
  }

  // 设置当前对话
  const setCurrentChat = (chatId) => {
    console.log(chatId)
    currentChatId.value = chatId
    const chat = currentChat.value
    // 获取对话记录详情
    getConversationDetail(chatId).then(res => {
      if (res.code === 200) {
        chat.messages = res.data.messages.map(
          (msg) => ({
            ...msg,
            content: msg.content.replace(/<think>([\s\S]*?)<\/think>/, ''),
            // 提取思考内容
            thinking: msg.content.match(/<think>([\s\S]*?)<\/think>/)?.[1] || '',
            finished: true
          })
        ) || []
      }
    })
  }

  // 添加消息到当前对话
  const addMessage = (message) => {
    const chat = currentChat.value
    if (chat) {
      chat.messages.push({
        id: nanoid(),
        ...message,
        created_at: new Date()
      })
      
      // 如果是第一条消息，更新对话标题
      if (chat.messages.length === 1 && message.is_user) {
        chat.title = message.content.substring(0, 20) + (message.content.length > 20 ? '...' : '')
        chat.isNew = false
      }
    }
  }

  // 删除对话
  const deleteChat = (chatId) => {
    // 删除对话记录
    deleteConversation(chatId).then(res => {
      if (res.code === 200) {
        const index = chatSessions.value.findIndex(chat => chat.session_id === chatId)
        if (index !== -1) {
          chatSessions.value.splice(index, 1)
          if (currentChatId.value === chatId) {
            resetChat()
          }
        }
        ElMessage.success('删除成功')
        setRecommendedQuestions()
      }
    })
  }

  // 重置对话
  const resetChat = () => {
    chatSessions.value = []
    currentChatId.value = null
    setChatSessions()
    // setRecommendedQuestions()
  }
  
  // 切换侧边栏状态
  const toggleSidebar = () => {
    isSidebarCollapsed.value = !isSidebarCollapsed.value
  }

//   设置对话列表
  const setChatSessions = () => {
    getConversationsList({
      page: 1,
      page_size: 50
    }).then(res => {
      console.log(res) // 打印API返回的对话列表
      if (res.code === 200) {
        chatSessions.value = res.data
        if (res.data?.length > 0) {
          setRecommendedQuestions()
        }
      }
    })
  }

  // 更新消息
  const updateMessage = (messageId, updates) => {
    const chat = currentChat.value
    if (chat) {
      const messageIndex = chat.messages.findIndex(msg => msg.id === messageId)
      if (messageIndex !== -1) {
        chat.messages[messageIndex] = {
          ...chat.messages[messageIndex],
          ...updates
        }
      }
    }
  }

  // 获取推荐问题
  const setRecommendedQuestions = () => {
    
    // 这里可以调用API获取推荐问题
    const lastSession = chatSessions.value?.[0] || {}
    if (!lastSession?.session_id) {
      recommendedQuestions.value = []
      return
    }
    getRecommendedQuestions().then(res => {
      if (res.code === 200) {
        recommendedQuestions.value = res.data.questions || []
      }
    })
  }

  // 设置发送状态
  const setIsSending = (value) => {
    isSending.value = value
  }

  return {
    chatSessions: computed(() => chatSessions.value),
    currentChatId,
    currentChat,
    isSidebarCollapsed,
    createNewChat,
    setCurrentChat,
    addMessage,
    deleteChat,
    toggleSidebar,
    resetChat,
    setChatSessions,
    updateMessage,
    setRecommendedQuestions,
    recommendedQuestions: computed(() => recommendedQuestions.value),
    isSending: computed(() => isSending.value),
    setIsSending
  }
})